package com.blensmile.anims;

/**
 * Created by Blensmile on 2016/7/16.
 */

import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.view.ViewGroup.MarginLayoutParams;

/**
 * 默认初始是展开的,需要默认折叠,需要在初始化需要动画的控件时主动调用setCollapseState
 */
public class ExpandAnimation extends Animation {

    private View view;
    private MarginLayoutParams mViewLayoutParams;
    private int mMarginStart, mMarginEnd;
    private boolean mIsVisibleAfter = false;
    private boolean mWasEndedAlready = false;

    public ExpandAnimation(View v, long duration) {
        setDuration(duration);
        this.view = v;
        mViewLayoutParams = (MarginLayoutParams) view.getLayoutParams();
        view.measure(0, 0);
        if (view.getVisibility() == View.GONE) {
            mViewLayoutParams.bottomMargin = 0 - view.getMeasuredHeight();
            view.setLayoutParams(mViewLayoutParams);
        }
        mIsVisibleAfter = (mViewLayoutParams.bottomMargin == 0);
        mMarginStart = mViewLayoutParams.bottomMargin;
        mMarginEnd = (mMarginStart == 0) ? (0 - view.getMeasuredHeight()) : 0;
        view.setVisibility(View.VISIBLE);
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        super.applyTransformation(interpolatedTime, t);
        if (interpolatedTime < 1f) {
            mViewLayoutParams.bottomMargin = mMarginStart + (int) ((mMarginEnd - mMarginStart) * interpolatedTime);
            view.requestLayout();
        } else if (!mWasEndedAlready) {
            mViewLayoutParams.bottomMargin = mMarginEnd;
            view.requestLayout();
            if (mIsVisibleAfter)
                view.setVisibility(View.GONE);
            mWasEndedAlready = true;
        }
    }

    @Override
    public void start() {
        super.start();
    }

    //
    public static void setCollapseState(View view) {
        view.measure(0, 0);
        MarginLayoutParams params = (MarginLayoutParams) view.getLayoutParams();
        params.setMargins(0, 0, 0, 0 - view.getMeasuredHeight());
        view.setLayoutParams(params);
    }
}